﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Data.SqlClient;
using System.Configuration;
using log4net;
using System.Reflection;

namespace ConnectionHttpModule
{
    [assembly: log4net.Config.XmlConfigurator(ConfigFile = "Log4Net.config", Watch = true)]
    public class ConnectionManager:IHttpModule
    {
        //log4net.ILog log = LogManager.GetLogger(typeof(Test));

        private static readonly string KEY_MSSQL_CONNECTION = "MssqlConnection";
        private static SqlConnection conn;
        private static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
        //private static readonly ILog Log = LogManager.GetLogger("ConnectionHttpModule");

        #region IHttpModule Members

        public void Dispose()
        {
            if (conn != null)
            {
                if (conn.State == System.Data.ConnectionState.Open)
                    conn.Close();
                conn.Dispose();
            }
        }

        public void Init(HttpApplication context)
        {

            context.BeginRequest += new EventHandler(context_BeginRequest);
            context.EndRequest += new EventHandler(context_EndRequest);
            context.Error += new EventHandler(context_Error);
        }

        void context_Error(object sender, EventArgs e)
        {
            
        }

        void context_EndRequest(object sender, EventArgs e)
        {
            HttpApplication application = (HttpApplication)sender;
            HttpContext context = application.Context;
            string extension = context.Request.PhysicalPath.Substring(context.Request.PhysicalPath.Length - 4);
            SqlConnection conn = context.Items[KEY_MSSQL_CONNECTION] as SqlConnection;
            if (conn != null && conn.State == System.Data.ConnectionState.Open)
            {
                conn.Close();
                SqlConnection.ClearPool(conn);
                SqlConnection.ClearAllPools();
                conn.Dispose();
            }
            context.Items[KEY_MSSQL_CONNECTION] = null;
            Log.Debug("Zatvora konekcija\n");
        }

        void context_BeginRequest(object sender, EventArgs e)
        {
            HttpApplication application = (HttpApplication)sender;
            HttpContext context = application.Context;
            string extension = context.Request.PhysicalPath.Substring(context.Request.PhysicalPath.Length - 4);
            if (extension == "aspx" || extension == "asmx")
            {
                context.Items[KEY_MSSQL_CONNECTION] = CreateConnection(ConfigurationSettings.AppSettings["ConnString1"]);
            }
            Log.Debug("Otvora konekcija\n");
        }

        public static SqlConnection CreateConnection(string s)
        {
            conn = new SqlConnection(s);
            //conn.Open();
            return conn;
        }

        public static SqlConnection CurrentConnection
        {
            get
            {
                if (HttpContext.Current == null)
                {
                    if (conn != null)
                    {
                        return conn;
                    }
                    else
                    {
                        conn = CreateConnection(ConfigurationSettings.AppSettings["ConnString1"]);
                        return conn;
                    }
                }
                else
                {
                    HttpContext contex = HttpContext.Current;
                    SqlConnection c = contex.Items[KEY_MSSQL_CONNECTION] as SqlConnection;
                    if (c == null)
                        c = CreateConnection(ConfigurationSettings.AppSettings["ConnString1"]);
                    return c;
                } 
            }
        }
        #endregion
    }
}
